package com.wyj.filter;

import com.wyj.util.RedisKeyUtil;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：wyj
 * @description：TODO
 * @date ：2022/12/9 2:24 下午
 */

@WebFilter(urlPatterns = "/user/*",filterName = "JpaFilter")
public class JpaFilter implements Filter {
    @Resource
    RedisTemplate redisTemplate;

    @Resource
    RedisKeyUtil redisKeyUtil;
    
    
    //init() ：该方法在容器启动初始化过滤器时被调用，它在 Filter 的整个生命周期只会被调用一次。注意：这个方法必须执行成功，否则过滤器会不起作用。
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
        Filter.super.init(filterConfig);
    }
    //doFilter() ：容器中的每一次请求都会调用该方法， FilterChain 用来调用下一个过滤器 Filter。
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        System.out.println("过滤器的执行方法");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //查看该用户的toke token是否过期
        val uuid = request.getHeader("token");
        val token = redisKeyUtil.getToken(uuid);
        Long expire = redisTemplate.getExpire(token);
       // val o = redisTemplate.opsForValue().get(token);

        if (expire > 0) {
            filterChain.doFilter(request, response);
        }else {
            response.sendRedirect("/unLogin");
        }

    }

    //当容器销毁 过滤器实例时调用该方法，一般在方法中销毁或关闭资源，在过滤器 Filter 的整个生命周期也只会被调用一次
    @Override
    public void destroy() {
        System.out.println("当服务器关闭的时候过滤完毕");
        Filter.super.destroy();
    }
}

